<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // promis
        // let p = new Promise((resolve, reject) => {
        //     console.log(1111);
        //     // console.log(resolve, reject);
        //     setTimeout(() => {
        //         resolve('执行完毕');
        //     }, 1000);
        // })
        // console.log(p);
        // p
        // .then(res => console.log(res, p))
    </script>
    <script>
        // 简易实现promise
        /*
            promise拥有三个状态
                1、pending
                2、fulfilled || rejected
        */
        function MyPromise(callBack) {
            //    定义一个状态
            this.status = 'pending';
            // 定义成功和失败的执行队列
            this.resolveArr = [];
            this.rejectArr = [];
            // 声明两个函数
            let resolve = (value) => {
                // 改变状态
                this.status = 'fulfilled';
                // 执行成功的队列
                this.resolveArr.forEach(fn => value = fn(value))
                // 清空队列
                this.resolveArr = [];
            }
            let reject = (value) => {
                // 改变状态
                this.status = 'rejected';
                // 执行失败时的队列
                this.rejectArr.forEach(fn => value = fn(value))
                // 清空队列
                this.rejectArr = [];
            }
            // 执行回调函数
            try {
                callBack(resolve, reject);
            } catch (e) {
                reject(e);
            }
        }
        // 设置then方法
        MyPromise.prototype.then = function(success, fail) {
            // 判断状态
            if (this.status == 'pending') {
                // 两个都添加
                typeof success == 'function' && this.resolveArr.push(success);
                typeof fail == 'function' && this.rejectArr.push(fail);
            } else if (this.status == 'fulfilled') {
                // 添加成功的
                typeof success == 'function' && this.resolveArr.push(success);
            } else {
                // 添加失败的
                typeof fail == 'function' && this.rejectArr.push(fail);
            }
            // 为了连续打点带调用
            return this;
        }
        let p = new MyPromise((resolve, reject) => {
            console.log(11111);
            setTimeout(() => {
                reject('执行失败');
            }, 1000);
        })
        console.log(p);
        p
        .then(res => {
            console.log(res, p)
            return 'sy103';
        }, err => console.log('error', err))
        .then(res => console.log(res))
    </script>
</body>

</html>